#include<iostream>
#include <memory>
#include <vector>
#include <cstring>
#include <cerrno>
#include <ctype.h>
#include "udp_server.hpp"

using namespace std;
using namespace ns_server;

bool isIllegalCommands(string str)
{
  //排查非法操作
  vector<string> vs = {{"rm"}, {"mv"}, {"kill"}, {"while :; do"}, {"shutdown"}};

  for(auto &e : vs)
  {
    if(str.find(e) != string::npos)
      return true;
  }

  return false;
}

string remoteCommands(string str)
{
  if(isIllegalCommands(str)) return "Warning, illegal operation!";

  FILE* pf = popen(str.c_str(), "r");
  if(!pf)
  {
    cerr << "popen fail: " << strerror(errno) << endl;
    fclose(pf);
    return "";
  }

  string retStr;
  char line[1024] = { 0 };
  while(fgets(line, sizeof line, pf))
    retStr += line;

  return retStr;
}

string stringUp(string str)
{
  //字符串中的字符大写化
  for(auto &e : str)
  {
    if(isalpha(e))
     e = toupper(e);
  }

  return str;
}

void Usage(char* argv[])
{
  cout << "Usage:" << endl;
  cout << "\t" << argv[0] << " Port" << endl;
}

int main(int argc, char* argv[])
{
  if(argc != 2)
  {
    Usage(argv);
    return USAGE_ERR;
  }

  unique_ptr<UdpServer> usvr(new UdpServer(remoteCommands, atoi(argv[1])));

  //首先初始化服务器
  usvr->StartServer();

  //然后启动服务器
  usvr->Recv();

  return 0;
}
